from flask import Flask, jsonify

import os
import click
from faker import Faker

from app.apis.v1 import api_v1
from app.blueprints.admin import admin_bp
from app.models import User, Setting, AddressBook
from app.settings import config
from app.extensions import db, migrate, csrf, login_manager

basedir = os.path.abspath(os.path.dirname(os.path.dirname(__file__)))


def create_app(config_name=None):
    if config_name is None:
        config_name = os.getenv('FLASK_CONFIG', 'development')
    app = Flask('app')
    app.config.from_object(config[config_name])

    register_blueprints(app)
    register_extensions(app)
    register_errors(app)
    register_shell_context(app)
    register_commands(app)
    return app


def register_blueprints(app):
    app.register_blueprint(admin_bp)
    app.register_blueprint(api_v1, url_prefix='/api/v1')


def register_extensions(app):
    db.init_app(app)
    login_manager.init_app(app)
    csrf.init_app(app)
    csrf.exempt(api_v1)
    migrate.init_app(app, db)


def register_shell_context(app):
    @app.shell_context_processor
    def make_shell_context():
        return dict(db=db, User=User, AddressBook=AddressBook)


def register_errors(app):
    @app.errorhandler(404)
    def page_not_found(e):
        response = jsonify(code=404, message='The requested URL was not found on the server.')
        response.status_code = 404
        return response

    @app.errorhandler(405)
    def method_not_allowed(e):
        response = jsonify(code=405, message='The method is not allowed for the requested URL.')
        response.status_code = 405
        return response

    @app.errorhandler(500)
    def internal_server_error(e):
        response = jsonify(code=500, message='An internal server error occurred.')
        response.status_code = 500
        return response


def register_commands(app):
    @app.cli.command()
    @click.option('--drop', is_flag=True, help='重建数据库')
    def initdb(drop):
        if drop:
            click.confirm('这个操作会删除你的数据库，确定吗？', abort=True)
            db.drop_all()
            click.echo('删除数据表')
        db.create_all()
        user = User(mobile='18888888888', is_admin=True)
        user.set_password('123456')
        db.session.add(user)
        config = Setting(title='Money', name='thawne', bank='招商银行', card_number='123546')
        db.session.add(config)
        db.session.commit()
        click.echo('初始化数据库')
